<?php

namespace App\Console\Commands\Tools\DbExport\Order;

use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Order\Service\OrderDb;
use App\Kuafu\Order\Service\OrderTable;
use App\Kuafu\Pay\BasePay;
use App\Kuafu\Pay\Channel\FuYou\FuYouBase;
use App\Kuafu\Pay\Service\PayService;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Service\ShopCameraSyncService;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Library\FeiShu\SendFs;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use League\Csv\Reader;

class OrderAllDbImportCommand extends Command
{

    protected $signature = 'tools:order-all-db-import';

    protected $description = '';

    public function handle()
    {
        ini_set('memory_limit', '2G');

        // shopId
        $shopId   = '14691';
        $isUpdate = false; // 更新导入

        // 存储位置
        $path  = storage_path() . '/import/';
        $files = File::files($path);

        foreach ($files as $file) {
            $fileName = $file->getFilename();
            $this->doHandle($path, $fileName, $shopId, $isUpdate);
        }
    }

    private function doHandle($path, $fileName, $shopId, $isUpdate = false)
    {
        // 主键 ID
        $tableName  = self::filterFileName($fileName);
        $primaryKey = OrderAllDbExportCommand::getPrimaryId($tableName);

        $this->info($tableName . ' 开始导入...');

        $csv = Reader::createFromPath($path . $fileName, 'r');
        $csv->setHeaderOffset(0); // 设置CSV中包含头部信息

        $orderDbConnection = OrderAllDbExportCommand::getOrderDbConnection($tableName, $shopId);
        DB::transaction(function () use ($csv, $shopId, $tableName, $orderDbConnection, $primaryKey, $isUpdate) {
            $insertData = [];
            foreach ($csv as $record) {
                // 特殊处理字段
                $record = self::specialHandle($record);

                if ($isUpdate) {
                    DB::connection($orderDbConnection)
                      ->table($tableName)
                      ->updateOrInsert([
                          $primaryKey => $record[$primaryKey]
                      ], $record);
                } else {
                    $insertData[] = $record;
                    if (count($insertData) >= 1000) {
                        DB::connection($orderDbConnection)
                          ->table($tableName)
                          ->insert($insertData);
                        $insertData = [];
                    }
                }
            }

            if (count($insertData) > 0) {
                DB::connection($orderDbConnection)
                  ->table($tableName)
                  ->insert($insertData);
            }
        });

        $this->info($tableName . ' 导入成功');
        $this->info('---------------------------------');
    }

    private function filterFileName($fileName): string
    {
        $list = explode('_', $fileName);
        unset($list[count($list) - 1]);
        return implode('_', $list);
    }

    private function specialHandle($record)
    {
        // 特殊处理外卖的某个字段
        if (isset($record['commodities']) && empty($record['commodities'])) {
            $record['commodities'] = null;
        }

        return $record;
    }
}
